/*
 * Copyright 2011 CyberSMS.ru
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ru.cybersms.model;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import ru.cybersms.CyberSms;

/**
 *
 * @author Андрей Шерцингер <support@cybersms.ru>
 */
public class JsonDateConverter
		implements JsonSerializer<Date>, JsonDeserializer<Date> {

	@Override
	public JsonElement serialize(Date src, Type srcType, JsonSerializationContext context) {
		DateFormat dateFormat = new SimpleDateFormat(CyberSms.DATE_TIME_FORMAT);
		dateFormat.setTimeZone(CyberSms.TIME_ZONE_UTC);
		if (src != null) {
			return new JsonPrimitive(dateFormat.format(src));
		}
		return new JsonPrimitive("");
	}

	@Override
	public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context)
			throws JsonParseException {
		try {
			String str = json.getAsString();
			if (str.length() == CyberSms.DATE_TIME_FORMAT.length()) {
				SimpleDateFormat sdf = new SimpleDateFormat(CyberSms.DATE_TIME_FORMAT);
				sdf.setTimeZone(CyberSms.TIME_ZONE_UTC);
				return sdf.parse(str);
			}	else if (str.length() == CyberSms.DATE_FORMAT.length()) {
				SimpleDateFormat sdf = new SimpleDateFormat(CyberSms.DATE_FORMAT);
				sdf.setTimeZone(CyberSms.TIME_ZONE_UTC);
				return sdf.parse(str);
			} else {
				throw new JsonParseException("CyberSms API:Illegal datetime or date format");
			}
		} catch (ParseException ex) {
			throw new JsonParseException(ex.getMessage(), ex);
		} catch (IllegalArgumentException e) {
			// May be it came in formatted as a java.util.Date, so try that
			Date date = context.deserialize(json, Date.class);
			return date;
		}
	}
}
